package edu.thu.studio.ormdesigner.editor.action;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;

import edu.thu.studio.ormdesigner.editor.editpart.NodeEditPart;
import edu.thu.studio.ormdesigner.editor.editpart.TableNodeEditPart;
import edu.thu.studio.ormdesigner.editor.editpart.ViewNodeEditPart;
import edu.thu.studio.ormdesigner.model.diagram.node.Node;
import edu.thu.studio.ormdesigner.util.Properties;

public class CopyAction extends AbstractSelectionAction {

	public CopyAction(IWorkbenchPart part) {
		super(part);
		this.setId(ActionFactory.COPY.getId());

		this.setText(Properties.action_title_copy);

		ISharedImages sharedImages = PlatformUI.getWorkbench()
				.getSharedImages();
		setImageDescriptor(sharedImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
		setDisabledImageDescriptor(sharedImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
	}

	@Override
	@SuppressWarnings("unchecked")
	protected boolean calculateEnabled() {
		List<EditPart> list = new ArrayList<EditPart>(this.getSelectedObjects());

		if (list.isEmpty()) {
			return false;
		}

		if (list.size() == 1
				&& (list.get(0) instanceof TableNodeEditPart || list.get(0) instanceof ViewNodeEditPart)) {
			return true;
		}

		return false;
	}

	@Override
	public void run() {
		CopyManager.clear();
		copy();
	}

	private void copy() {

		if (!calculateEnabled()) {
			return;
		}

		for (Object object : this.getSelectedObjects()) {
			if (object instanceof NodeEditPart) {
				NodeEditPart editPart = (NodeEditPart) object;
				Node node = (Node) editPart.getModel();
				CopyManager.copy(node);
			}
		}
	}
}
